<template></template>

<script setup>
// 合并请求的例子
async function fetchData() {
  try {
    const responses = await Promise.all([
      fetch("/api/user/profile"),
      fetch("/api/user/notifications"),
      fetch("/api/user/messages")
    ]);

    const data = await Promise.all(responses.map(res => res.json()));

    const userData = {
      profile: data[0],
      notifications: data[1],
      messages: data[2]
    };

    return userData;
  } catch (error) {
    console.error("请求失败", error);
  }
}

// 懒加载图片示例
const lazyLoadImages = () => {
  const images = document.querySelectorAll("img.lazy");

  const loadImage = image => {
    const src = image.getAttribute("data-src");
    if (src) {
      image.src = src;
      image.classList.remove("lazy");
    }
  };

  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        loadImage(entry.target);
        observer.unobserve(entry.target);
      }
    });
  });

  images.forEach(image => observer.observe(image));
};

// 页面加载后调用懒加载函数
window.onload = lazyLoadImages;

// 防抖函数
function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), delay);
  };
}

// 使用防抖优化搜索框输入
const searchInput = document.querySelector("#search");
searchInput.addEventListener(
  "input",
  debounce(function (e) {
    fetch(`/api/search?q=${e.target.value}`);
  }, 300)
);

// 节流函数
function throttle(func, wait) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= wait) {
      lastTime = now;
      func(...args);
    }
  };
}

// 使用节流优化滚动事件
window.addEventListener(
  "scroll",
  throttle(function () {
    console.log("滚动中...");
  }, 1000)
);

// 缓存 API 请求的示例
async function fetchDataWithCache(url) {
  const cacheKey = `cache-${url}`;
  const cachedData = localStorage.getItem(cacheKey);

  if (cachedData) {
    return JSON.parse(cachedData);
  } else {
    const response = await fetch(url);
    const data = await response.json();
    localStorage.setItem(cacheKey, JSON.stringify(data));
    return data;
  }
}

fetchDataWithCache("/api/data").then(data => console.log(data));

// 使用 Promise.all 处理多个 AJAX 请求
async function fetchData() {
  const requests = [
    fetch("/api/user"),
    fetch("/api/orders"),
    fetch("/api/products")
  ];

  try {
    const responses = await Promise.all(requests);
    const data = await Promise.all(responses.map(response => response.json()));

    console.log(data); // 所有数据都返回了
  } catch (error) {
    console.error("请求失败", error);
  }
}

// Web Worker 示例
if (window.Worker) {
  const worker = new Worker("worker.js");

  worker.onmessage = function (e) {
    console.log("来自 worker 的消息:", e.data);
  };

  worker.postMessage("开始计算");
}

onmessage = function (e) {
  console.log("收到消息:", e.data);
  postMessage("计算完成");
};

// 延迟加载外部 JavaScript
function loadScript(src) {
  const script = document.createElement("script");
  script.src = src;
  document.head.appendChild(script);
}

window.onload = function () {
  loadScript("https://example.com/external-script.js");
};
</script>
<script>
export default {
  name: ""
};
</script>

<style lang="scss" scoped></style>
